package com.imddysc.springbootmultidatasources.config;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
		entityManagerFactoryRef = "entityManagerFactorySecond", 
		transactionManagerRef = "transactionManagerSecond", 
		basePackages = {
		"com.imddysc.springbootmultidatasources.secondrepository" }) //设置dao（repo）所在位置
public class SecondJpaConfig {

	@Autowired
	@Qualifier("secondDataSource")
	private DataSource secondDataSource;

	@Autowired
	private JpaProperties jpaProperties;

	@Bean(name = "entityManagerFactorySecond")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
		return builder
				.dataSource(secondDataSource)
				.properties(jpaProperties.getProperties())
				.packages("com.imddysc.springbootmultidatasources.secondentity") // 设置实体类所在位置
				.persistenceUnit("secondPersistenceUnit")
				.build();
	}

	@Bean(name = "entityManagerSecond")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
	}

	@Bean(name = "transactionManagerSecond")
	PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
	}
	
}
